import os
from datetime import datetime
import hashlib
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_migrate import Migrate
from werkzeug.middleware.proxy_fix import ProxyFix
from config import Config

def md5_filter(s):
    return hashlib.md5(s.encode('utf-8')).hexdigest()

# 创建扩展实例
db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.login_message = '请先登录以访问此页面'

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    # 初始化扩展
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)

    # 应用 ProxyFix 中间件
    # x_proto=1: 信任 X-Forwarded-Proto (http/https)
    # x_host=1: 信任 X-Forwarded-Host (域名)
    app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)

    # 添加模板上下文处理器
    @app.context_processor
    def inject_current_year():
        return {'current_year': datetime.now().year}

    # 注册模板过滤器
    app.jinja_env.filters['md5'] = md5_filter

    # 注册蓝图
    with app.app_context():
        from app.routes.main import main_bp
        from app.routes.auth import auth_bp
        from app.routes.admin import admin_bp
        from app.routes.music import music_bp
        from app.routes.game import game_bp

        app.register_blueprint(main_bp)
        app.register_blueprint(music_bp, url_prefix='/music')
        app.register_blueprint(auth_bp, url_prefix='/auth')
        app.register_blueprint(admin_bp, url_prefix='/admin')
        app.register_blueprint(game_bp, url_prefix='/game')

    return app